package com.pro.common.cursor.sync.service;

import com.pro.common.api.cursor.sync.enums.EnumCursorValueType;
import com.pro.framework.api.enums.ITaskCursorKey;
import com.pro.common.api.cursor.sync.model.db.SysTaskCursor;
import com.pro.common.cursor.sync.dao.SysTaskCursorDao;
import com.pro.framework.mybatisplus.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class SysTaskCursorService extends BaseService<SysTaskCursorDao, SysTaskCursor> {

    public SysTaskCursor getByTaskKey(ITaskCursorKey taskKey) {
        return lambdaQuery().eq(SysTaskCursor::getTaskKey, taskKey).one();
    }

    public long getLongCursor(ITaskCursorKey taskKey, long defaultValue) {
        return parseLongSafe(getCursorValue(taskKey), defaultValue);
    }

    public LocalDateTime getTimeCursor(ITaskCursorKey taskKey, LocalDateTime defaultValue) {
        return parseDateTimeSafe(getCursorValue(taskKey), defaultValue);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateLongCursor(ITaskCursorKey taskKey, long newValue, String remark) {
        upsertCursor(taskKey, String.valueOf(newValue), remark, EnumCursorValueType.LONG);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateTimeCursor(ITaskCursorKey taskKey, LocalDateTime newValue, String remark) {
        upsertCursor(taskKey, newValue.toString(), remark, EnumCursorValueType.TIMESTAMP);
    }

    @Transactional(rollbackFor = Exception.class)
    public void upsertCursor(ITaskCursorKey taskKey, String cursorValue, String remark, EnumCursorValueType valueType) {
        SysTaskCursor cursor = getByTaskKey(taskKey);
        if (cursor == null) {
            cursor = new SysTaskCursor();
            cursor.setTaskKey(taskKey.name());
            cursor.setCursorValue(cursorValue);
            cursor.setRemark(remark);
            cursor.setValueType(valueType);
            save(cursor);
        } else {
            cursor.setCursorValue(cursorValue);
            cursor.setRemark(remark);
            cursor.setValueType(valueType);
            updateById(cursor);
        }
    }

    public String getCursorValue(ITaskCursorKey taskKey) {
        SysTaskCursor cursor = getByTaskKey(taskKey);
        return cursor != null ? cursor.getCursorValue() : null;
    }

    private long parseLongSafe(String value, long defaultValue) {
        if (value == null) return defaultValue;
        try {
            return Long.parseLong(value);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    private LocalDateTime parseDateTimeSafe(String value, LocalDateTime defaultValue) {
        if (value == null) return defaultValue;
        try {
            return LocalDateTime.parse(value);
        } catch (Exception e) {
            return defaultValue;
        }
    }
}
